package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static com.hmdp.content.RedisConstants.KEY_PRFIX;

public class SimpleRedisLock implements ILock {


    private StringRedisTemplate stringRedisTemplate;
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate,String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT  = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    /**
     * 获取锁
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(Long timeoutSec) {
        String key = KEY_PRFIX+name;
        String threadid = ID_PREFIX+Thread.currentThread().getId();
        Boolean succes = stringRedisTemplate.opsForValue().setIfAbsent(key, threadid, timeoutSec, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(succes);
    }

    /**
     * 释放锁
     */
    @Override
    public void unLock() {


        // 获取线程标识
        String threadid = ID_PREFIX+Thread.currentThread().getId();
        //获取锁中的
        String lockKey = KEY_PRFIX+name;
//        String lockid = stringRedisTemplate.opsForValue().get(lockKey);
//
//        //判断表示是否一致
//        if (threadid.equals(lockid))
//        {
//            //释放锁
//            stringRedisTemplate.delete(lockKey);
//        }
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(lockKey),
                threadid);
    }
}
